package com.ruoyi.web.controller;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在SpringBoot中，常用的异常处理有两种，一种是BasicErrorController，
 * 另一种是@ControllerAdvice，BasicErrorController用于处理非Controller抛出的异常，
 * 而@ControllerAdvice用于处理Controller抛出的异常，对于非Controller抛出的异常它是不会管的。
 * 但是，如果是Controller层调用Service层，从Service层抛出，依然会抛到Controller，
 * 所以还是会调用@ControllerAdvice进行处理处理非业务异常。
 * BasicErrorController是一个控制器，对/error进行处理，如果有错误，会被重定向到 /error ，然后交给 BasicErrorController 处理
 */
@RestController
public class ErrorController extends BasicErrorController {

    private static final String PATH = "/error";

    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }


    @RequestMapping(produces = {"text/html"})
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("/404");
    }

    /**
     * 处理全局异常没有捕获的异常(当前端是数据格式是application/json时)
     *
     * @param request
     * @return
     */
    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity error(HttpServletRequest request) {
        AjaxResult error = AjaxResult.error(HttpStatus.NotFound.getCode(), HttpStatus.NotFound.getMessage());
        return new ResponseEntity(error, org.springframework.http.HttpStatus.NOT_FOUND);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}
